<template>
	<img
		ref="imgRef"
		v-show="!type || loaded || !defaultImg"
		:class="classList"
		:src="src"
		alt=""
		v-bind="$attrs" />
	<img
		v-if="type && !loaded && defaultImg"
		:class="classList"
		:src="defaultImg"
		alt=""
		v-bind="$attrs" />
</template>

<script lang="ts">
export default {
	inheritAttrs: false
}
</script>

<script setup lang="ts">
import { ref, nextTick, onMounted, Ref, onBeforeUnmount, computed, PropType } from 'vue'
import { getImgUrl } from './image.ts'

export type ImagePropsType = {
	src: string
	type: 'server' | 'network' | '' | string
	default: string
}

const emit = defineEmits(['onload'])
const props = defineProps({
	src: {
		type: String as PropType<ImagePropsType['src']>,
		default: ''
	},
	type: {
		type: String as PropType<ImagePropsType['type']>,
		default: ''
	},
	default: {
		type: String as PropType<ImagePropsType['default']>,
		default: ''
	},
	rounded: {
		type: Boolean,
		default: false
	},
	color: {
		type: String,
		default: ''
	}
})

const classList = ['base-image', { 'rounded-lg': props.rounded }]

//如果不传type默认是从../../../assets/img/src`路径取
const src = computed(() => {
	if (props.type === 'network') {
		return props.src
	} else if (props.type === 'server' && props.src) {
		return import.meta.env.VITE_IMAGE_URL + props.src
	}
	return getImgUrl(props.src || props.default)
})

const defaultImg = computed(() => getImgUrl(props.default))

const imgRef = ref<Ref<HTMLImageElement> | null>(null)

const loaded = ref(false)

const onLoad = () => {
	loaded.value = true
	nextTick(() => {
		emit('onload')
	})
}

onMounted(() => {
	if (props.type && props.src) {
		imgRef.value?.addEventListener('load', onLoad)
	}
})

onBeforeUnmount(() => {
	if (props.type && props.src) {
		imgRef.value?.removeEventListener('load', onLoad)
	}
})
</script>
<style scoped>
/* .base-image {
	width: 20px;
	height: 20px;
} */
</style>
